import React, {Component} from 'react';
import {withRouter,Link, Switch, Route} from 'react-router-dom'
import 'moment/locale/zh-cn';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import { LocaleProvider } from 'antd';
import 'moment/locale/zh-cn';
import u from '../../common.js'
import $ from 'jquery'
import locale from 'antd/lib/date-picker/locale/zh_CN';
import Loading from "./../loading"//加载中样式
import { Layout, Menu,  Icon ,Button,Table, Form, Modal,Input,Radio,Pagination, DatePicker, message} from 'antd';
import '../../static/icon/iconfont.css'



import "../../static/systemSetup/system-base.styl"

const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { RangePicker, MonthPicker } = DatePicker;




export default class SystemRange extends React.Component{
    //表格配置项
    state = {
      selectedRowKeys: [],//选中项
      selectedRows:[],//选中项的值
        visible: false,
        visible2: false,
        visible3: false,
        visible4: false,
        value: 1,
        dataArr:[],//采集范围数组
        URLs:[],//url数组
        singleID:[],//要删除的单个ID
        editRowKey:{},//要修改的关键词
        text:'暂无任何数据',
    }
    start = () => {
        setTimeout(() => {
          this.setState({
            selectedRowKeys: [],
    
          });
        }, 1000);
      }
    //获取选中的行以及选中行的值
    onSelectChange =(selectedRowKeys, selectedRows) => {
      this.setState({ 
        selectedRowKeys:selectedRowKeys,
        selectedRows:selectedRows,
      });
      

    }
    //弹出框 
    addKeywords = () => {
        this.setState({
          visible: true,
        });
      }
    
      delKeywords =(id)=>{
        let IDarr=[];
        IDarr.push(id)
        this.setState({
          visible2: true,
          singleID:IDarr,
        },()=>{
          console.log(this.state.singleID)
        });
       
      }

      editKeywords =(val)=>{
        console.log(val)
        this.setState({
              visible3: true,
              editRowKey:val
            });
      } 
     
      //删除采集范围
      delKey =(e) =>{
        let delArr= this.state.selectedRows;
    let ids=[];//要删除的黑名单的id
    for(var i=0;i<delArr.length;i++){
      ids.push(delArr[i].id)
    } 
    console.log(ids)
    console.log(this.state.singleID)
        u.delCollection({
          ids:ids.length > 0 ? ids : this.state.singleID,
        },data=>{
          console.log(data)
            this.setState({
             visible: false,
             visible2: false,
             visible3: false,
             selectedRowKeys:[],
             selectedRows:[]
           });
          //  window.location.reload();
           this.showRange();
        })
      }
        //修改采集范围  
        editKey =(e) =>{
          this.setState({
            visible: false,
            visible2: false,
            visible3: false,
            visible4:true,//复制层打开
          });
   
          setTimeout(()=>{
            let siteURL=this.state.editRowKey.URL
            let siteName=this.state.editRowKey.siteName
            // let keyType=this.state.selectedRows[0].key_type
            document.getElementById("siteURL2").value=siteURL
            document.getElementById("siteName2").value=siteName
            $('.ant-calendar-range-picker-input:nth-of-type(1)').val(this.state.editRowKey.start_time)
            $('.ant-calendar-range-picker-input:nth-of-type(2)').val(this.state.editRowKey.end_time) 
          },1000);

        }
        //点击确定 修改采集范围
        editThiskey=()=>{
         
           //修改采集范围接口
        u.editCollection({
          domain:document.getElementById("siteURL2").value,
          website:document.getElementById("siteName2").value,
          startTime:$('.ant-calendar-range-picker-input:nth-of-type(1)').val(),
          endTime:$('.ant-calendar-range-picker-input:nth-of-type(2)').val(),
          id:this.state.editRowKey.id,
          status:this.state.editRowKey.status
        },data =>{
         let key=this.state.editRowKey.ID-1;
         let arr=this.state.dataArr.slice(0)
         arr[key].URL=document.getElementById("siteURL2").value
         arr[key].siteName=document.getElementById("siteName2").value
         arr[key].collection= $('.ant-calendar-range-picker-input:nth-of-type(1)').val()+'  '+$('.ant-calendar-range-picker-input:nth-of-type(2)').val()
           this.setState({
             dataArr:arr
           })

        }
        )
        this.setState({
          visible4:false,
        })//('修改采集')
        }
    //点击确定
    handleOk = (e) => {
      let siteURLVal=$.trim($('.siteURL').val())
      let siteName=$.trim($('.siteName').val())
     //非空验证
      if(siteURLVal.length < 1){
        message.error('请先输入网站URL');
        return
      }else if(siteName.length < 1){
        message.error('请先输入网站名称');
        return
      }

           //添加采集范围
           let rangeArr={
            domain:siteURLVal,
            website:siteName,
            startTime:$('.ant-calendar-range-picker-input:nth-of-type(1)').val(),
            endTime:$('.ant-calendar-range-picker-input:nth-of-type(2)').val(),
            status:0,
           }
        u.addCollection(rangeArr,data=>{
           let arr = this.state.dataArr.slice(0)
           //表格的数据
           let key = {
                 ID: arr.length+1,
                 URL: $('.siteURL').val(),
                 siteName: $('.siteName').val(),
                 collection: $('.ant-calendar-range-picker-input:nth-of-type(1)').val()+'  '+$('.ant-calendar-range-picker-input:nth-of-type(2)').val(),
                 status:0,
               }
               this.state.dataArr.forEach(item=>{
                this.state.URLs.push(item.URL)
            })
            //重复验证
            if($.inArray(siteURLVal,this.state.URLs) >= 0){
              message.error('网站地址重复');
              return
            }else{
              // arr.push(key);
              this.setState({
                visible: false,
              });
              // window.location.reload();
              this.showRange();
            }
         })
         setTimeout(()=>{
          $('.siteURL').val('')
          $('.siteName').val('')
        },1000)
      }
         //点击取消
         handleCancel = (e) => {
          this.setState({
            visible: false,
            visible2: false,
            visible3: false,
            visible4:false,
          });
        } 
      //单选框
      onChange = (e) => {
        this.setState({
          value: e.target.value,
        });
      }
      itemRender=(current, type, originalElement)=> {
        if (type === 'prev') {
          return <a>上一页</a>;
        } if (type === 'next') {
          return <a>下一页</a>;
        }
        return originalElement;
      }
      //封装渲染方法
      showRange=()=>{
        u.getCollection(data=>{
          data.data.forEach(item => {
            item.ID=data.data.indexOf(item)+1,
            item.URL=item.domain,
            item.siteName=item.website,
            item.collection=item.start_time+'  '+item.end_time,
            item.status=item.status
          });
          this.setState((prevState)=>({
            dataArr:data.data
          }))//渲染出来的所有采集范围
        })
      }
      //第一次渲染
      componentDidMount(){
        this.showRange()
      }
    render(){
        const state = this.state;
          const {  selectedRowKeys } = this.state;
          const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
          };
          const hasSelected = selectedRowKeys.length > 0;
          //表格
const columns = [{
  title: 'ID',
  dataIndex: 'ID',
  key: 'ID',
  width: 70,
 
}, {
  title: '网站URL',
  dataIndex: 'URL',
  key: 'URL',
  width: 200,
}, {
  title: '网站名称',
  dataIndex: 'siteName',
  key: 'siteName',
  width: 350,
}, {
  title: '采集周期',
  dataIndex: 'collection',
  key: 'collection',
  width: 120,
},
{
  title: '状态',
  dataIndex: 'status',
  key: 'status',
  width: 200,
},
{
  title: '操作',
  key: 'action',
  width: 200,
  render: (text, record) => (
    <span style={{whiteSpace:"nowrap",display:"flex",justifyContent:"space-between",width:"50%",marginLeft:"25%"}}>
      <a href="javascript:;" className="modify" style={{color:"#5286ff"}} onClick={()=>{this.editKeywords(record)}} >
      <img src={require("../../static/image/icon-edit.png")} alt=""/>
       修改
      </a>
      <a href="javascript:;" className="del" onClick={()=>{this.delKeywords(record.id)}}>
      {/* <img src={require("../../static/image/icon-del.png")} alt=""/> */}
      <i className="iconfont icon-territory_del"></i>
      删除</a>
    </span>
  ),
}
];

        return(

            <div className="container">
               <Loading className="loadingPage"/>
               <Layout>
                  
                    <Layout>
                        <Content style={{ background: '#fff', margin: 0, minHeight: 280 , overflowY:"hidden"}}> 
                          <div className="btns-center">
                            <div className="options" style={{marginTop:"0"}}>
                                <Button className="btnBorder" onClick={this.delKeywords}>删除</Button>
                                <Button  onClick={this.addKeywords} className="btnBorder">添加</Button>
                                {/* 添加采集范围 */}
                                <Modal              
                                    className='addStyle'              
                                    title={<span>
                                    <span className='addStyleFont'>添加采集范围</span></span>}
                                    visible={this.state.visible}
                                    // onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                      <Button  onClick={this.handleCancel}>
                                        取 消
                                      </Button>,
                                      <Button onClick={this.handleOk} type="primary">
                                        确 定
                                      </Button>,
                                    ]}
                                    >
                                    <div className="addRow">
                                      <div className="label">
                                        <span>网站URL:</span>
                                       </div>
                                       <Input placeholder="请输入网站URL" style={{width:"60%"}} size="default" className='siteURL'/>
                                    </div>
                                    <div className="addRow">
                                       <div className="label">
                                         <span>网站名称:</span>
                                       </div>
                                       <Input className="input-area" placeholder="请输入网站名称" style={{width:"60%"}} className='siteName'/>
                                    </div>
                                    <div className="addRow">
                                      <div className="label">
                                        <span>采集周期:</span>
                                      </div>
                                        <RangePicker renderExtraFooter={() => 'extra footer'} locale={locale} style={{marginLeft:"1%",width:"60%"}}/>
                                    </div>
                                </Modal>
                                         {/* 复制的添加采集范围 */}
                                     
                                <Modal           
                                    className='addStyle'                  
                                    title={<span>
                                    <span className='addStyleFont'>添加采集范围</span></span>}
                                    visible={this.state.visible4}
                                    // onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                      <Button  onClick={this.handleCancel}>
                                        取 消
                                      </Button>,
                                      <Button onClick={this.editThiskey} type="primary">
                                        确 定
                                      </Button>,
                                    ]}
                                    >
                                    <div className="addRow">
                                      <div className="label">
                                        <span>网站URL:</span>
                                       </div>
                                       <Input placeholder="请输入网站URL" style={{width:"60%"}} size="default" id='siteURL2'/>
                                    </div>
                                    <div className="addRow">
                                       <div className="label">
                                         <span>网站名称:</span>
                                       </div>
                                       <Input className="input-area" placeholder="请输入网站名称" style={{width:"60%"}} id='siteName2'/>
                                    </div>
                                    <div className="addRow">
                                      <div className="label">
                                        <span>采集周期:</span>
                                      </div>
                                        <RangePicker className='rangeDate' renderExtraFooter={() => 'extra footer'} locale={locale} style={{marginLeft:"1%",width:"60%"}}/>
                                    </div>
                                </Modal>
                                {/* 删除采集范围 */}
                                <Modal
                                className='delStyle'
                                  title={<span>
                                  <span className='delStyleFont'>删除</span></span>}
                                  visible={this.state.visible2}
                                  //  onOk={this.handleOk}
                                   onCancel={this.handleCancel}
                                   centered='true'
                                  footer={[
                                    <Button  onClick={this.handleCancel}>
                                      取消
                                    </Button>,
                                    <Button onClick={this.delKey} type="primary">
                                      确定
                                    </Button>,
                                  ]}
                                >
                                   <p style={{marginLeft:"10%",marginBottom:"10%"}}>是否删除该采集范围？</p>
                                </Modal>
                                 {/* 修改采集范围 */}
                                 <Modal
                                 className='delStyle'
                                  title={<span>
                                  <span className='delStyleFont'>修改</span></span>}
                                  visible={this.state.visible3}
                                  //  onOk={this.handleOk}
                                   onCancel={this.handleCancel}
                                   centered='true'
                                  footer={[
                                    <Button  onClick={this.handleCancel}>
                                      取消
                                    </Button>,
                                    <Button onClick={this.editKey} type="primary">
                                      确定
                                    </Button>,
                                  ]}
                                >
                                   <p style={{marginLeft:"10%",marginBottom:"10%"}}>是否修改该采集范围？</p>
                                </Modal>
                            </div>
                            {/* 表格 */}
                            
                             
                            <Table {...this.state} columns={columns} dataSource={this.state.dataArr} rowSelection={rowSelection} pagination={true}
                              style={{marginBottom:"2%"}} id='loadTable' locale={{emptyText:this.state.text}}
                            />
                          </div>
                          
                        </Content>
                    </Layout>
                    </Layout>
                
           </div>
        );
    }
}